package network_programming.np1_socket_and_serversocket;

import java.io.*;
import java.net.Socket;

public class EchoClient {
    private String host = "localhost";  // 服务器主机
    private int port = 9099;            // 服务器端口号
    Socket socket;                      // 套接字，两端通信的收发器
    public EchoClient() throws IOException {
        socket = new Socket(host, port);
    }
    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketOS = socket.getOutputStream();
        return new PrintWriter(socketOS, true);
    }
    private BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketIS = socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketIS));
    }
    public void talk() {
        try {
            BufferedReader br = getReader(socket);
            PrintWriter pw = getWriter(socket);
            BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
            String msg = null;
            while((msg = localReader.readLine()) != null) {
                pw.println(msg);
                System.out.println(br.readLine());
                if(msg.equals("bye"))
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new EchoClient().talk();
    }
}
